import {
  app,
  shell,
  BrowserWindow,
  desktopCapturer,
  ipcMain,
  screen,
  globalShortcut
} from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import pool from './mysql/pool'

// pool
let mainWindow2: any = null
function createWindow(): void {
  // Create the browser window.
  const { width, height } = screen.getPrimaryDisplay().workAreaSize

  const mainWindow = new BrowserWindow({
    titleBarOverlay: true,
    // titleBarStyle:"hidden",
    // frame: false,
    width: width * 0.5,
    height: height * 0.5,
    show: false,
    title: 'My App', // 这里设置应用程序的标题
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      // webSecurity: false,
      nodeIntegration: true,
      contextIsolation: false,
      devTools: true
    }
  })

  // 在主进程中监听渲染进程发送的截屏请求
  ipcMain.on('capture-screen', async (event, { x, y, width, height }) => {
    const { desktopCapturer } = require('electron')
    const { writeFile } = require('fs').promises

    // 使用 desktopCapturer 模块获取屏幕截图
    const sources = await desktopCapturer.getSources({ types: ['screen'] })
    const source = sources.find((source) => source.id === 'screen:0:0')

    if (!source) {
      // 如果未找到屏幕源，发送错误消息给渲染进程
      event.sender.send('capture-screen-error', 'Failed to capture screen: source not found')
      return
    }
    const imgData = await source.thumbnail.toPNG()
    const { nativeImage } = require('electron')
    console.log('获取截图数据成功1')
    const image = nativeImage.createFromBuffer(imgData)
    if (image.isEmpty()) {
      console.error('创建 nativeImage 对象失败2')
      return
    }
    console.log('创建 nativeImage 对象成功3')
    const croppedImage = image.crop({ x, y, width, height })
    if (croppedImage.isEmpty()) {
      console.log(x, y, width, height)

      console.error('裁剪图像失败4')
      return
    }
    console.log('裁剪图像成功5')
    await writeFile('./path', croppedImage.toPNG())
    console.log('保存文件成功6')

    // // 使用 source.thumbnail 对象获取屏幕截图数据
    // const imgData = await source.thumbnail.toPNG()

    // // 根据用户选择的区域裁剪截图
    // const { nativeImage } = require('electron')
    // const image = nativeImage.createFromBuffer(imgData)
    // const croppedImage = image.crop({ x, y, width, height })

    // 将截图保存为文件或者将图片数据发送给渲染进程，这里仅演示保存为文件的操作
    // const filePath = './path'
    // await writeFile(filePath, croppedImage.toPNG())

    event.reply('capture-screen-success', filePath)
    // 发送截图文件路径给渲染进程
    event.sender.send('capture-screen-success', filePath)
  })

  // //  ---------------------------------------------  开启第二个窗口

  ipcMain.on('get-open-window2', (e, item) => {
    // console.log('open-window2', e, item)

    if (item.openWindows2) {
      app.whenReady().then(() => {
        const { screen } = require('electron')
        const primaryDisplay = screen.getPrimaryDisplay()
        // const { width, height } = primaryDisplay.workAreaSize
        mainWindow2 = new BrowserWindow({
          width: 800,
          height: 600,
          frame: false, // 无边框
          transparent: true, // 窗口透明
          alwaysOnTop: true, // 窗口总在最前
          webPreferences: {
            preload: join(__dirname, '../preload/index.js'),
            nodeIntegration: true,
            contextIsolation: false
          }
        })

        mainWindow2.loadFile('src/main/screen.html')
        mainWindow2.setFullScreen(true)
        mainWindow2.setIgnoreMouseEvents(false)
        // mainWindow2.loadURL('../../src/renderer/index.html')
        // mainWindow2.loadURL('https://electronjs.org')
      })
    }
  })

  // 关闭第二个窗口
  ipcMain.on('get-close-window2', (e, item) => {
    // console.log('close-window2', e, item)
    if (item.closeWindows2) {
      mainWindow2.close()
    }
  })

  //  ---------------------------------------------  获取Windows  id
  ipcMain.on('get-window-id', (event) => {
    console.log(event)
    event.reply('window-id', mainWindow.id)
  })

  //  ---------------------------------------------  获取当前鼠标所在的位置 x,y
  ipcMain.on('get-mouse-position', (event) => {
    const mousePos = screen.getCursorScreenPoint()
    console.log(`鼠标位置：X=${mousePos.x}, Y=${mousePos.y}`)
    // 如果需要，也可以把位置信息发送回渲染器进程
    event.reply('mouse-position', mousePos)
  })
  //  ---------------------------------------------  最小化当前窗口
  ipcMain.on('minimize-window', () => {
    mainWindow.minimize()
  })

  //  ---------------------------------------------  获取当前屏幕的图片
  ipcMain.handle('CAPTURE_SCREEN', async (event, args) => {
    // const { desktopCapturer } = require('electron')
    const sources = await desktopCapturer.getSources({
      types: ['screen'],
      thumbnailSize: { width: 1920, height: 1080 }
    })
    return sources[0].thumbnail.toPNG().toString('base64')
  })

  //  ---------------------------------------------   获取当前打开的窗口
  ipcMain.handle('get-desktop-sources', async () => {
    const sources = await desktopCapturer.getSources({ types: ['window', 'screen'] })
    return sources
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
}) 

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
// app.on('window-all-closed', () => {
//   if (process.platform !== 'darwin') {
//     app.quit()
//   }
// })

// app.on('ready', () => {
//   // 注册全局快捷键
//   const ret = globalShortcut.register('Escape', () => {
//     console.log('Escape was pressed')
//     // 在这里可以加入关闭窗口等其他操作

//   })
//   globalShortcut.register('F2', () => {
//     console.log('F2')
//   })

//   if (!ret) {
//     console.log('registration failed')
//   }

//   // 检查快捷键是否注册成功
//   console.log('globalShortcut.isRegistered:::', globalShortcut.isRegistered('Escape'))
// })

// app.on('will-quit', () => {
//   // 注销快捷键
//   globalShortcut.unregister('Escape')
//   // 注销所有快捷键
//   globalShortcut.unregisterAll()
// })

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.

// ---------------------------------------------------------------------------------------------------------------------透明窗口

// let mainWindow2: any = null
// function createWindow2() {
//   //  ---------------------------------------------  开启第二个窗口

//   ipcMain.on('get-open-window2', (e, item) => {
//     // console.log('open-window2', e, item)

//     if (item.openWindows2) {
//       app.whenReady().then(() => {
//         const { screen } = require('electron')
//         const primaryDisplay = screen.getPrimaryDisplay()
//         // const { width, height } = primaryDisplay.workAreaSize
//         mainWindow2 = new BrowserWindow({
//           width: 800,
//           height: 600,
//           frame: false, // 无边框
//           transparent: true, // 窗口透明
//           alwaysOnTop: true, // 窗口总在最前
//           webPreferences: {
//             preload: join(__dirname, '../preload/index.js'),
//             nodeIntegration: true,
//             contextIsolation: false
//           }
//         })

//         mainWindow2.loadFile('src/main/screen.html')
//         mainWindow2.setFullScreen(true)
//         mainWindow2.setIgnoreMouseEvents(false)
//         // mainWindow2.loadURL('../../src/renderer/index.html')
//         // mainWindow2.loadURL('https://electronjs.org')
//       })
//     }
//   })

//   // 关闭第二个窗口
//   ipcMain.on('get-close-window2', (e, item) => {
//     console.log('close-window2', e, item)
//     if (item.closeWindows2) {
//       mainWindow2.close()
//     }
//   })
// }

// 数数据库初始化  pool
// app.pool = pool
   